<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-bounce.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"zhiruozzy.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":"truw","sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="同步和异步同步任务：在主线程上排队执行的任务，只有前一个任务执行完之后，才能执行下一个任务 异步任务：不进入主线程，而是进入任务队列的任务，只有任务队列通知主线程某个异步任务可以执行了，这个任务才可以进入主线程执行">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajex自学笔记">
<meta property="og:url" content="http://zhiruozzy.cn/2022/03/27/Ajex/index.html">
<meta property="og:site_name" content="芷若">
<meta property="og:description" content="同步和异步同步任务：在主线程上排队执行的任务，只有前一个任务执行完之后，才能执行下一个任务 异步任务：不进入主线程，而是进入任务队列的任务，只有任务队列通知主线程某个异步任务可以执行了，这个任务才可以进入主线程执行">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-27T06:34:29.000Z">
<meta property="article:modified_time" content="2022-04-07T14:08:27.023Z">
<meta property="article:author" content="芷若">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://zhiruozzy.cn/2022/03/27/Ajex/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Ajex自学笔记 | 芷若</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">芷若</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-主页">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>主页</a>

  </li>
        <li class="menu-item menu-item-关于">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-标签">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-目录">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>目录</a>

  </li>
        <li class="menu-item menu-item-归档">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container"></div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="algolia-results">
  <div id="algolia-stats"></div>
  <div id="algolia-hits"></div>
  <div id="algolia-pagination" class="algolia-pagination"></div>
</div>

      
    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/zhiruozzy" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://zhiruozzy.cn/2022/03/27/Ajex/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/touxiang.jpg">
      <meta itemprop="name" content="芷若">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="芷若">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Ajex自学笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-03-27 14:34:29" itemprop="dateCreated datePublished" datetime="2022-03-27T14:34:29+08:00">2022-03-27</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-04-07 22:08:27" itemprop="dateModified" datetime="2022-04-07T22:08:27+08:00">2022-04-07</time>
              </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="同步和异步"><a href="#同步和异步" class="headerlink" title="同步和异步"></a>同步和异步</h2><p>同步任务：在主线程上排队执行的任务，只有前一个任务执行完之后，才能执行下一个任务</p>
<p>异步任务：不进入主线程，而是进入任务队列的任务，只有任务队列通知主线程某个异步任务可以执行了，这个任务才可以进入主线程执行</p>
<span id="more"></span>

<p>比如：网络图片的请求就是一个异步任务，谁先请求完成就让谁先显示出来。</p>
<p>常见异步的场景：</p>
<ol>
<li>定时器：setTimeout (经过指定时间之后执行该函数，一次执行) 、setinterval（反复执行）</li>
<li>事件的绑定函数，比如按钮绑定点击事件，用户只有点击了按钮才会执行，所以是异步</li>
<li>网络请求：ajax请求（前端发送Ajax请求向后端请求数据，然后等待一段时间才能拿到这个数据，所以这个请求过程就是异步任务），网络图片加载</li>
<li>ES6中的Promise</li>
</ol>
<h2 id="异步任务举例"><a href="#异步任务举例" class="headerlink" title="异步任务举例"></a>异步任务举例</h2><h4 id="预加载图片"><a href="#预加载图片" class="headerlink" title="预加载图片"></a>预加载图片</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"><span class="keyword">function</span> <span class="title function_">loadImage</span>(<span class="params">url, callback</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> img = <span class="keyword">new</span> <span class="title class_">Image</span>(); <span class="comment">//创建一个Image对象，实现图片的预下载</span></span></span><br><span class="line"><span class="language-javascript">    img.<span class="property">src</span> = url;</span></span><br><span class="line"><span class="language-javascript">    </span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">if</span> (img.<span class="property">complete</span>) &#123; <span class="comment">// 如果图片已经存在于浏览器缓存，直接调用回调函数</span></span></span><br><span class="line"><span class="language-javascript">     callback.<span class="title function_">call</span>(img); </span></span><br><span class="line"><span class="language-javascript">     <span class="keyword">return</span>; <span class="comment">// 直接返回，不用再处理onload事件</span></span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    img.<span class="property">onload</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123; <span class="comment">//图片下载完毕时异步调用callback函数。</span></span></span><br><span class="line"><span class="language-javascript">      callback.<span class="title function_">call</span>(img);<span class="comment">//将回调函数的this替换为Image对象</span></span></span><br><span class="line"><span class="language-javascript">    &#125;;</span></span><br><span class="line"><span class="language-javascript">&#125;;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"><span class="comment">//被回调的方法</span></span></span><br><span class="line"><span class="language-javascript"><span class="keyword">function</span> <span class="title function_">imgLoaded</span>(<span class="params"></span>)&#123;</span></span><br><span class="line"><span class="language-javascript"><span class="title function_">alert</span>(<span class="variable language_">this</span>.<span class="property">width</span>);</span></span><br><span class="line"><span class="language-javascript">&#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">value</span>=<span class="string">&quot;loadImage&quot;</span> ο<span class="attr">nclick</span>=<span class="string">&quot;loadImag(&#x27;xxx.jpg&#x27;,imgLoaded)&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>理解一下这段代码。</p>
<ul>
<li><p>首先先看HTML中给表单绑定了一个单击响应函数，函数的名字是loadImage，第一个参数是一个图片，第二个参数是一个函数（回调函数）</p>
</li>
<li><p>再看script中的loadImage函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">loadImage</span>(<span class="params">url, callback</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> img = <span class="keyword">new</span> <span class="title class_">Image</span>(); <span class="comment">//创建一个Image对象，实现图片的预下载</span></span><br><span class="line">    img.<span class="property">src</span> = url;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (img.<span class="property">complete</span>) &#123; <span class="comment">// 如果图片已经存在于浏览器缓存，直接调用回调函数，即调用imgLoaded,并将this指向改成了img</span></span><br><span class="line">     callback.<span class="title function_">call</span>(img); </span><br><span class="line">     <span class="keyword">return</span>; <span class="comment">// 直接返回，不用再处理onload事件</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    img.<span class="property">onload</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123; <span class="comment">//图片下载完毕时异步调用callback函数。</span></span><br><span class="line">      callback.<span class="title function_">call</span>(img);<span class="comment">//将回调函数的this替换为Image对象</span></span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>要理解这个函数，必须知道以下知识：</p>
<p>image 的 **onload ** 事件     </p>
<p>&#x3D;&gt;onload事件在图片加载完成之后立即执行代码</p>
<p>语法：onload&#x3D;”<em>JavaScriptCode</em>“</p>
<p>image 的 <strong>complete</strong> 属性</p>
<p>&#x3D;&gt;可返回浏览器是否完成对图像的加载，如果加载完成，则返回true，否则返回false</p>
<p>语法：imageObject.complete</p>
<p><strong>callback.call</strong></p>
<p>callback是一种函数，为回调函数，一般来说，函数A的参数是函数B，那么就发生了回调。</p>
<p><strong>call()方法</strong>：可以调用一个函数，并改变这个函数内部的this指向。</p>
<p>语法：function1.call(你想要this指向哪里，function1的实参1，function1的实参2…)</p>
<p>如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    <span class="attr">nickName</span>: <span class="string">&#x27;zhizhi&#x27;</span>,</span><br><span class="line">    <span class="attr">age</span>: <span class="number">18</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fn1</span>(<span class="params">a, b</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">nickName</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(a + b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fn1.<span class="title function_">call</span>(obj1, <span class="number">2</span>, <span class="number">4</span>); <span class="comment">// 先将 this 指向 obj1，然后执行 fn1() 函数</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>最后看一下回调函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//被回调的方法</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">imgLoaded</span>(<span class="params"></span>)&#123;</span><br><span class="line"><span class="title function_">alert</span>(<span class="variable language_">this</span>.<span class="property">width</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>即调用这个函数后，会弹出this指向的对象的宽度</p>
</li>
</ul>
<h2 id="全局刷新和局部刷新"><a href="#全局刷新和局部刷新" class="headerlink" title="全局刷新和局部刷新"></a>全局刷新和局部刷新</h2><ol>
<li><p>全局刷新</p>
<ul>
<li><p>用表单form、herf等发起的请求是全局刷新，用户发起请求，视图发生了改变，页面发生跳转。</p>
</li>
<li><p>缺点：渲染新的页面需要时间，占用了网络带宽。如果数据量很大，那么耗时将很长，用户体验性不好。</p>
</li>
</ul>
</li>
<li><p>局部刷新</p>
<ul>
<li><p>在当前页面中发送请求，获取数据，更新当前页面的dom对象，对视图部分刷新。</p>
</li>
<li><p>比如访问微博的时候，点击底部的加载更多，会自动帮我们加载更多的微博，同时页面并不会整体刷新。</p>
</li>
<li><p>优点：①只获取少量数据，速度传输更快。</p>
<p>​            ②部分更新页面，速度很快。</p>
<p>​            ③在一个页面中，可以做多个局部刷新</p>
</li>
</ul>
</li>
</ol>
<h2 id="异步对象"><a href="#异步对象" class="headerlink" title="异步对象"></a>异步对象</h2><p>创建方法：<br><code>var xhr = new XMLHttpRequest();</code></p>
<p>使用异步对象主要负责发起请求，传递请求的参数，并从服务器接收数据</p>
<p> 局部刷新需要使用的技术：</p>
<ol>
<li>JavaScript：创建异步对象，调用它的属性和方法</li>
<li>dom：处理dom来更新数据</li>
<li>css：处理视图，美化</li>
<li>servlet：服务器端技术</li>
<li>json</li>
</ol>
<p>把以上这些技术综合应用就叫做Ajax，他不是新的编程语言，而是多种技术的综合应用。AJax全称为asynchronous JavaScript and XML（异步的JavaScript和XML）。我们使用Ajax来实现局部刷新</p>
<h2 id="异步对象的属性和方法"><a href="#异步对象的属性和方法" class="headerlink" title="异步对象的属性和方法"></a>异步对象的属性和方法</h2><ol>
<li><p>创建异步对象</p>
<p><code>var xhr = new XMLHttpRequest(); </code>  </p>
</li>
<li><p>异步对象的方法</p>
<ul>
<li><p>open（请求方式，服务器端的访问地址，是否为异步方式），用来建立http请求</p>
<p>例如：<code>xhr.open(&quot;GET&quot;,url,true);</code></p>
<p>注意：请求方式大小写不敏感，是否为异步方式默认为true</p>
</li>
<li><p>send ( body ), 用于建立链接后发送请求</p>
</li>
</ul>
</li>
<li><p>异步对象的属性</p>
<ul>
<li><p><strong>readyState</strong>：表示请求的状态</p>
<p>0：创建异步对象时（new对象）</p>
<p>1：建立请求时（执行open方法）</p>
<p>2：使用send方法发送请求时</p>
<p>3：使用异步对象从服务端接收了数据</p>
<p>4：异步对象接受并处理完数据</p>
</li>
<li><p><strong>status</strong>：表示网络的状态，和http的状态码对应</p>
<p>如：200 请求成功| 404服务器资源没有找到</p>
</li>
<li><p><strong>responseText</strong>: 获得字符串形式的响应数据</p>
<p>如：<code>var data = xhr.responseText</code></p>
</li>
<li><p><strong>responseXML</strong>：获得XML形式的响应数据</p>
</li>
</ul>
</li>
</ol>
<h2 id="异步对象的使用步骤"><a href="#异步对象的使用步骤" class="headerlink" title="异步对象的使用步骤"></a>异步对象的使用步骤</h2><ol>
<li><p>使用JS创建异步对象，即XMLHttpRequest对象</p>
<p>var xhr &#x3D; new XMLHttpRequest();</p>
</li>
<li><p>使用open()方法设置请求参数。open(method,url,true&#x2F;false);</p>
</li>
<li><p>发送请求，执行send()函数</p>
</li>
<li><p>给异步对象绑定事件，事件名称onreadystatechange，状态改变时就会调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">xhr.<span class="title function_">onreadystatechange</span>()=<span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    当状态改变时执行的代码</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果在数据完整并且请求回来的时候才调用的话，需要在绑定的函数中用if语句来加以判断，例子如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">xhr.<span class="title function_">onreadystatechange</span>()=<span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="comment">//从服务器中获取了数据</span></span><br><span class="line">   <span class="keyword">if</span>(xhr.<span class="property">readyState</span>==<span class="number">4</span> &amp;&amp; xhr.<span class="property">status</span>==<span class="number">200</span>)&#123;</span><br><span class="line">     <span class="keyword">var</span> data = xhr.<span class="property">reponseText</span>;</span><br><span class="line">     <span class="comment">//更新dom对象</span></span><br><span class="line">     <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;mydiv&quot;</span>).<span class="property">innerHTML</span> = data;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>服务端响应，获取返回的数据</p>
</li>
</ol>
<h2 id="发送请求的方式是POST"><a href="#发送请求的方式是POST" class="headerlink" title="发送请求的方式是POST"></a>发送请求的方式是POST</h2><p>方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">open</span>(method,url,<span class="literal">true</span>/<span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<p>当method时POST请求时要注意，如果想像form表单提交数据那样使用POST请求，需要使用<strong>XMLHttpRequest</strong> 对象的**setRequestHeader()**来添加HTTP头，并在send（）方法中添加想要发送的数据。</p>
<p>例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;POST&#x27;</span>, <span class="string">&#x27;ajax_test.php&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">xmlhttp.<span class="title function_">setRequestHeader</span>(<span class="string">&#x27;Content-type&#x27;</span>, <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);<span class="comment">//请求头是数据的类型，application/x-www-form-urlencoded：表单发送默认格式</span></span><br><span class="line"></span><br><span class="line">xmlhttp.<span class="title function_">send</span>(<span class="string">&#x27;name=smyhvae&amp;age=27&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><p>setRequestHeader(header, value)    header字符串:http请求头   value 字符串:值。</p>
<h4 id="常见请求头"><a href="#常见请求头" class="headerlink" title="常见请求头"></a>常见请求头</h4><table>
<thead>
<tr>
<th>请求头字段</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>Accept</td>
<td>客户端可接受的MIME类型</td>
</tr>
<tr>
<td>Content-Type</td>
<td>数据属于什么类型，如js,c++,html,text格式</td>
</tr>
<tr>
<td>User-Agent</td>
<td>发出请求的用户信息，如用户使用的什么客户端</td>
</tr>
<tr>
<td>Cookie</td>
<td>客户端保存服务器返回的数据，如保存用户身份信息</td>
</tr>
<tr>
<td>Connection</td>
<td>表示处理完这次请求后是否断开链接</td>
</tr>
</tbody></table>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/03/27/HTTP/" rel="prev" title="HTTP自学笔记">
      <i class="fa fa-chevron-left"></i> HTTP自学笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/03/30/%E7%A6%BB%E6%95%A3%E6%95%B0%E5%AD%A6%E3%81%AE%E7%AC%94%E8%AE%B0/" rel="next" title="离散数学の笔记">
      离散数学の笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5"><span class="nav-number">1.</span> <span class="nav-text">同步和异步</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E4%B8%BE%E4%BE%8B"><span class="nav-number">2.</span> <span class="nav-text">异步任务举例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%A2%84%E5%8A%A0%E8%BD%BD%E5%9B%BE%E7%89%87"><span class="nav-number">2.0.1.</span> <span class="nav-text">预加载图片</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%A8%E5%B1%80%E5%88%B7%E6%96%B0%E5%92%8C%E5%B1%80%E9%83%A8%E5%88%B7%E6%96%B0"><span class="nav-number">3.</span> <span class="nav-text">全局刷新和局部刷新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E5%AF%B9%E8%B1%A1"><span class="nav-number">4.</span> <span class="nav-text">异步对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B1%9E%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95"><span class="nav-number">5.</span> <span class="nav-text">异步对象的属性和方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4"><span class="nav-number">6.</span> <span class="nav-text">异步对象的使用步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82%E7%9A%84%E6%96%B9%E5%BC%8F%E6%98%AFPOST"><span class="nav-number">7.</span> <span class="nav-text">发送请求的方式是POST</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%AD%E6%B3%95"><span class="nav-number">7.1.</span> <span class="nav-text">语法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B8%B8%E8%A7%81%E8%AF%B7%E6%B1%82%E5%A4%B4"><span class="nav-number">7.1.1.</span> <span class="nav-text">常见请求头</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="芷若"
      src="/images/touxiang.jpg">
  <p class="site-author-name" itemprop="name">芷若</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">19</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/zhiruo" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zhiruo" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2022001874号 </a>
      <img src="http://www.beian.gov.cn/portal/download" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="芷若"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">芷若</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">105k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:35</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="//cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script>
<script src="//cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script>
<script src="/js/algolia-search.js"></script>














  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/assets/koharu.model.json"},"display":{"position":"right","width":145,"height":315},"mobile":{"show":true,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.8},"log":false});</script></body>
</html>
